// 处理复杂的渲染计算
self.onmessage = function(e) {
    try {
        const { type, data, messageId } = e.data;

        switch (type) {
            case 'render':
                {
                    const { objects, canvasWidth, canvasHeight } = data;

                    // 计算对象的位置和变换
                    const processedObjects = objects.map(obj => {
                        // 添加碰撞检测
                        const collisions = detectCollisions(obj, objects);
                        
                        return {
                            ...obj,
                            calculatedPosition: {
                                x: obj.left,
                                y: obj.top
                            },
                            collisions,
                            // 添加变换矩阵计算
                            transform: calculateTransform(obj)
                        };
                    });

                    // 发送处理后的结果
                    self.postMessage({
                        messageId,
                        data: {
                            objects: processedObjects,
                            canvasWidth,
                            canvasHeight
                        }
                    });
                    break;
                }

            case 'layout':
                {
                    const { objects, canvasWidth, canvasHeight, layoutType = 'grid' } = data;

                    // 根据布局类型选择不同的布局算法
                    let layout;
                    switch (layoutType) {
                        case 'grid':
                            layout = calculateGridLayout(objects, canvasWidth, canvasHeight);
                            break;
                        case 'force':
                            layout = calculateForceLayout(objects, canvasWidth, canvasHeight);
                            break;
                        default:
                            layout = calculateGridLayout(objects, canvasWidth, canvasHeight);
                    }

                    self.postMessage({
                        messageId,
                        data: layout
                    });
                    break;
                }

            default:
                throw new Error(`Unknown message type: ${type}`);
        }
    } catch (error) {
        self.postMessage({
            messageId,
            error: error.message
        });
    }
};

// 碰撞检测函数
function detectCollisions(obj, allObjects) {
    return allObjects
        .filter(other => other.id !== obj.id)
        .filter(other => {
            return (
                obj.left < other.left + other.width &&
                obj.left + obj.width > other.left &&
                obj.top < other.top + other.height &&
                obj.top + obj.height > other.top
            );
        })
        .map(other => other.id);
}

// 计算变换矩阵
function calculateTransform(obj) {
    // 这里可以添加更复杂的变换矩阵计算
    return {
        scaleX: obj.scaleX || 1,
        scaleY: obj.scaleY || 1,
        angle: obj.angle || 0,
        skewX: obj.skewX || 0,
        skewY: obj.skewY || 0
    };
}

// 网格布局算法
function calculateGridLayout(objects, canvasWidth, canvasHeight) {
    const gridSize = Math.ceil(Math.sqrt(objects.length));
    const cellWidth = canvasWidth / gridSize;
    const cellHeight = canvasHeight / gridSize;

    return {
        positions: objects.map((obj, index) => {
            const row = Math.floor(index / gridSize);
            const col = index % gridSize;
            return {
                id: obj.id,
                x: col * cellWidth + cellWidth / 2,
                y: row * cellHeight + cellHeight / 2
            };
        }),
        canvasWidth,
        canvasHeight
    };
}

// 力导向布局算法
function calculateForceLayout(objects, canvasWidth, canvasHeight) {
    const positions = objects.map(obj => ({
        id: obj.id,
        x: obj.left || Math.random() * canvasWidth,
        y: obj.top || Math.random() * canvasHeight,
        vx: 0,
        vy: 0
    }));

    // 简单的力导向布局实现
    for (let i = 0; i < 50; i++) {
        positions.forEach(p1 => {
            positions.forEach(p2 => {
                if (p1.id === p2.id) return;
                
                const dx = p2.x - p1.x;
                const dy = p2.y - p1.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance > 0) {
                    const force = 1000 / (distance * distance);
                    p1.vx -= (dx / distance) * force;
                    p1.vy -= (dy / distance) * force;
                }
            });
        });

        positions.forEach(p => {
            p.x += p.vx * 0.1;
            p.y += p.vy * 0.1;
            p.vx *= 0.9;
            p.vy *= 0.9;
        });
    }

    return {
        positions: positions.map(({ id, x, y }) => ({ id, x, y })),
        canvasWidth,
        canvasHeight
    };
}